<?php
/**
 * 用户登录
 * 同一IP的用户连续10次登录失败，此用户在一个小时内将不能再登录
 * @author Mortimer He <mortimerhe@163.com>
 */
namespace Manage\Controller;
use Think\Controller;
use Common\Library\ImageThumb;
class LoginController extends Controller{
	private $msg=array();
	public function index(){
		if(session(C('USER_AUTH_KEY'))) $this->redirect('Index/index');
		if(IS_POST){
			if($this->vilidateForm()){
				$this->redirect('Index/index');
			}
		}
		$this->assign('msg',$this->msg);
		$this->assign('heading_title',L('heading_title'));
		$this->display();
	}
	private function vilidateForm(){
		$data=I('post.','','trim');
		
		if(mb_strlen($data['username'])>40 || mb_strlen($data['username'])<2 || mb_strlen($data['password'])>40 || mb_strlen($data['password'])<6){
			$this->msg['warning_login']=L('error_login');
		}else{
			$client_ip=get_client_ip();
			$UserModel=M('User');
			$UserLogModel=M('UserLog');
			$now=time();
			$hour_ago=strtotime('-1 hour');
			$cmap=array(
				'ip'		=>	$client_ip,
				'status'	=>	0,
				'date_logged'=>array('between',array($hour_ago,$now))
				);
			$count=$UserLogModel->where($cmap)->count();
			if($count>10){
				$this->msg['warning_login']=L('error_to_more');
			}else{
				$map=array(
					'username'	=> $data['username'],
					'password'	=> md5(sha1($data['password']).C('DATA_AUTH_KEY')),
					'status'	=>	1
					);
				$user=array();
				$user=$UserModel->where($map)->find();

				if(!empty($user)){
					$ugmap=array(
						'status'	=>	1,
						'user_group_id'=>$user['user_group_id']
						);
					$user_group=M('UserGroup')->where($ugmap)->find();
					if(!empty($user_group)){
						session(C('USER_AUTH_KEY'),$user['user_id']);
						
						$cmap=array(
							'ip'	=>	$client_ip,
							'status'=> 0
							);
						$UserLogModel->where($cmap)->delete();
						$data=array(
							'ip'	=>	$client_ip,
							'status'=>	1,
							'date_logged'=>time(),
							'user_id'=>	$user['user_id']
							);
						$UserLogModel->add($data);
					}else{
						$this->msg['warning_login']=L('error_group_is_disabled');
					}
				}else{
					$this->msg['warning_login']=L('error_login');
					$data=array(
						'ip'		=>	$client_ip,
						'status'	=>	0,
						'date_logged'=>time()
						);
					$UserLogModel->add($data);
				}
			}
		}

		return !$this->msg;
	}

	public function logout(){
		session('[destroy]');
		$this->redirect('Login/index');
	}

}